import 'package:flutter/material.dart';
import 'dart:io';
import 'dart:async';
import 'package:path_provider/path_provider.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // TRY THIS: Try running your application with "flutter run". You'll see
        // the application has a purple toolbar. Then, without quitting the app,
        // try changing the seedColor in the colorScheme below to Colors.green
        // and then invoke "hot reload" (save your changes or press the "hot
        // reload" button in a Flutter-supported IDE, or press "r" if you used
        // the command line to start the app).
        //
        // Notice that the counter didn't reset back to zero; the application
        // state is not lost during the reload. To reset the state, use hot
        // restart instead.
        //
        // This works for code too, not just values: Most code changes can be
        // tested with just a hot reload.
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String _fileContent = '';
  final TextEditingController _textController = TextEditingController();
  String? _fileName;
  bool _isInitializing = true;

  @override
  void initState() {
    super.initState();
    _initFilePath();
  }

  Future<void> _initFilePath() async {
    try {
      final directory = await getApplicationDocumentsDirectory().timeout(
        const Duration(seconds: 5),
      );

      // 确保目录存在
      if (!await directory.exists()) {
        await directory.create(recursive: true);
      }

      final file = File('${directory.path}/example.txt');

      // 确保文件存在
      if (!await file.exists()) {
        await file.writeAsString('');
      }

      setState(() {
        _fileName = file.path;
        _isInitializing = false;
      });
    } on TimeoutException {
      setState(() {
        _fileContent = '路径获取超时，请检查存储权限';
        _isInitializing = false;
      });
    } on FileSystemException catch (e) {
      setState(() {
        _fileContent = '文件系统错误: ${e.message}';
        _isInitializing = false;
      });
    } catch (e) {
      setState(() {
        _fileContent = '初始化失败: ${e.toString()}';
        _isInitializing = false;
      });
    }
  }

  Future<void> _readFile() async {
    try {
      if (_fileName == null) {
        setState(() {
          _fileContent = '文件路径未初始化';
        });
        return;
      }
      final file = File(_fileName!);
      final contents = await file.readAsString();
      setState(() {
        _fileContent = contents;
      });
    } catch (e) {
      setState(() {
        _fileContent = 'Error reading file: $e';
      });
    }
  }

  Future<void> _writeFile() async {
    try {
      if (_fileName == null) {
        setState(() {
          _fileContent = '文件路径未初始化';
        });
        return;
      }
      final file = File(_fileName!);
      await file.writeAsString(_textController.text);
      setState(() {
        _fileContent = 'File written successfully!';
      });
    } catch (e) {
      setState(() {
        _fileContent = 'Error writing file: $e';
      });
    }
  }

  @override
  void dispose() {
    _textController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: <Widget>[
            TextField(
              controller: _textController,
              decoration: const InputDecoration(
                labelText: 'Enter text to save',
                border: OutlineInputBorder(),
              ),
              maxLines: 3,
            ),
            const SizedBox(height: 20),
            if (_isInitializing)
              const CircularProgressIndicator()
            else ...[
              ElevatedButton(
                onPressed: _fileName == null ? null : _writeFile,
                child: const Text('保存到文件'),
              ),
              const SizedBox(height: 20),
              ElevatedButton(
                onPressed: _fileName == null ? null : _readFile,
                child: const Text('从文件读取'),
              ),
            ],
            const SizedBox(height: 20),
            Expanded(
              child: SingleChildScrollView(
                child: Text(_fileContent, style: const TextStyle(fontSize: 16)),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
